package vip.rpai.notepad
//数据库以及ListView列表协同操作
import android.content.Context
import org.jetbrains.anko.db.delete
import org.jetbrains.anko.db.insert
import org.jetbrains.anko.db.select
import org.jetbrains.anko.db.update

class LeSS(private val context: Context) {
    val fruitAdapter = FruitAdapter(context)//ListView适配器

    companion object {
        //列表视图的数据
        val dataList = arrayListOf<Fruit>()

        val requestCodeAddInfoActivity = 1
        //表的各项属性
        const val DATABASE_NAME: String = "LexussDB"
        const val TABLE_NAME: String = "LexussTB"
        const val TB_ID: String = "id"
        const val TABLE_INFO: String = "info"
        const val TABLE_DATE: String = "date"
    }


    fun initData() {
        //这里从Sqlite里面读出数据
        dataList.clear()
        context.database.use {
            select(TABLE_NAME).exec {
                while (moveToNext()) {
                    val tempID = getColumnIndex(TB_ID)
                    val tempINFO = getColumnIndex(TABLE_INFO)
                    val tempDATE = getColumnIndex(TABLE_DATE)
                    val id = getInt(if (tempID >= 0) tempID else 0)
                    val info = getString(if (tempINFO >= 0) tempINFO else 0)
                    val date = getString(if (tempDATE >= 0) tempDATE else 0)
                    dataList.add(Fruit(id, info, date))
                }
            }
        }
        showData()
    }


    //添加一条数据到列表和数据库
    fun addDataAndInsert(fruit: Fruit) {
        dataList.add(fruit)
        showData()
        leInsert(fruit)
    }

    fun upDateData(position: Int, info: String, date: String) {
        val i = dataList[position]
        i.info = info
        i.date = date
        leUpDate(i)
    }

    fun reMoveData(indexs: ArrayList<Int>){
        //移除数据
        for (i in indexs)
            if (i < dataList.size && i >= 0) {
                leDelete(dataList[i].id)
                dataList.removeAt(i)
            }
        showData()
    }

    fun showData() {
        fruitAdapter.notifyDataSetChanged()
    }


    private fun leInsert(f: Fruit) {
        context.database.use {
            insert(
                TABLE_NAME,
                TB_ID to f.id,
                TABLE_INFO to f.info,
                TABLE_DATE to f.date
            )
        }
    }

    private fun leDelete(fid: Int) {
        context.database.use {
            delete(TABLE_NAME, "$TB_ID = {fid}", "fid" to fid)
        }
    }

    private fun leUpDate(fruit: Fruit) {
        context.database.use {
            update(
                TABLE_NAME, TABLE_INFO to fruit.info
            )
                .whereArgs("$TB_ID = {userId}", "userId" to fruit.id)
                .exec()
        }
    }
}